#!/usr/bin/tclsh

####
# Start in the current directory.
# Walk the file hierarchy.
# In each directory found containing mp3 files, write a m3u playlist containing every mp3.
# Playlist is written in the order files are listed by the [glob] command.
####

proc getDirs {} {
	set dirs ""
	if [catch {
		set dirs [glob -type d *]
	}] {
	}
	return $dirs
}


proc getMp3s {} {
	set mp3s ""
	if [catch {
		set mp3s [glob -type f *.mp3]
	}] {
	}
	return $mp3s
}

proc findFiles {} {
	set files [getMp3s]
	if {[llength $files] > 0} {
		puts "Writing playlist in directory [pwd]"
		set f [open playlist.m3u w]
		foreach file $files {
			puts $f $file
		} 
		close $f
	}
}

proc goIn { inDir } {
	cd $inDir
	set dirs [getDirs]
	if {[llength $dirs] == 0} {
		findFiles
		return 0
	}
	foreach dir $dirs {
		cd $dir
		if {[goIn [pwd]] == 0} {
			cd ..
			findFiles
		}
	}
	cd ..
}

goIn [pwd]


